﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace SearchUtil.ZeneSoft
{
    public class Engine
    {
        const string StatusApi = "apps/sf1r/instances/_/api/status";
        const string SearchApi = "apps/sf1r/instances/_/api/documents/search";
        const string IndexAPI = "apps/sf1r/instances/_/api/commands";

        public string Host { get; set; }
        public int Port { get; set; }
        public string Collection { get; set; }
        public string LogFilePath
        {
            get
            {
                return AppDomain.CurrentDomain.BaseDirectory + logFile;
            }
        }

        public string Config(string arg, ref Engine engineCurrent)
        {
            try
            {
                var arr = arg.Split(':');

                App.Default.Host = arr[0];
                App.Default.Port = int.Parse(arr[1]);
                App.Default.Collection = arr[2];

                App.Default.Save();

                engineCurrent = new ZeneSoft.Engine
                  {
                      Host = App.Default.Host,
                      Port = App.Default.Port,
                      Collection = App.Default.Collection
                  };

                return "已重新配置!";
            }
            catch (Exception e)
            {
                return string.Format("请输入正确的配置:{0},{1}", e.Message, e.StackTrace);
            }
        }

        public string GetByCode(string code)
        {
            var queryApi = string.Format("http://{0}:{1}/{2}", Host, Port, SearchApi);
            var jsonInput = "{\"collection\": \"" + Collection + "\",\"search\": {\"keywords\": \"" + code + "\",\"in\": [{\"property\": \"ProductCode\"}]}}";
            return GetFromSF1(queryApi, jsonInput);
        }

        public string GetByName(string name)
        {
            var queryApi = string.Format("http://{0}:{1}/{2}", Host, Port, SearchApi);
            var jsonInput = "{\"collection\": \"" + Collection + "\",\"search\": {\"keywords\": \"" + name
                + "\",\"in\": [{\"property\": \"Title\"},{\"property\": \"SubName\"},{\"property\": \"Author\"},{\"property\": \"PublishName\"},"
                + "{\"property\": \"CategoryName\"},{\"property\": \"MultipleWords\"},{\"property\": \"Isbn\"},{\"property\": \"ProductCode\"}"
                + "]}}";

            return GetFromSF1(queryApi, jsonInput);
        }

        public string GetByCustom(string pathInput)
        {
            var jsonInput = string.Empty;
            try
            {
                jsonInput = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + pathInput);
            }
            catch (Exception e)
            {
                return string.Format("无法读取输入json:{0},{1}", e.Message, e.StackTrace);
            }
            Console.WriteLine(jsonInput);
            var queryApi = string.Format("http://{0}:{1}/{2}", Host, Port, SearchApi);
            return GetFromSF1(queryApi, jsonInput);
        }

        public string QueryStatus()
        {
            var queryApi = string.Format("http://{0}:{1}/{2}", Host, Port, StatusApi);
            var jsonInput = "{\"collection\": \"" + Collection + "\"}";
            return GetFromSF1(queryApi, jsonInput);
        }

        public string ReIndex()
        {
            var queryApi = string.Format("http://{0}:{1}/{2}", Host, Port, IndexAPI);
            var jsonInput = "{\"collection\": \"" + Collection + "\"}";
            return GetFromSF1(queryApi, jsonInput);
        }

        public static string GetFromSF1(string queryApi, string jsonInput)
        {
            try
            {
                var encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(queryApi);
                request.Method = "POST";
                request.ContentType = "application/json";

                byte[] buffer = encoding.GetBytes(jsonInput);
                Stream stream = request.GetRequestStream();
                stream.Write(buffer, 0, buffer.Length);
                stream.Close();


                var result = string.Empty;

                using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                    {
                        result = reader.ReadToEnd();
                    }
                }

                LogAnToClipboard(jsonInput, result);
                return result;

            }
            catch (Exception e)
            {
                return string.Format("无法取到数据:{0},{1}", e.Message, e.StackTrace);
            }
        }

        const string logFile = "/log.txt";
        private static void LogAnToClipboard(string jsonInput, string jsonOut)
        {
            try
            {
                System.IO.File.AppendAllText(
                    AppDomain.CurrentDomain.BaseDirectory + logFile,
                    string.Format("*******时间:{0}**********\n输入Json:{1}\n输出Json{2}\n", DateTime.Now, jsonInput, jsonOut));

                System.Windows.Forms.Clipboard.SetText(jsonOut);
            }
            catch (Exception e)
            {
                Console.WriteLine("日志写入失败:{0},{1}", e.Message, e.StackTrace);
            }
        }

        public string ReadLog()
        {
            var logs = string.Empty;
            try
            {
                return System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + logFile);

            }
            catch (Exception e)
            {
                return string.Format("无法读取日志:{0},{1}", e.Message, e.StackTrace);
            }
        }


    }
}
